package com.example.backend.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backend.domain.entity.RestBean;
import com.example.backend.domain.po.Services;
import com.example.backend.service.IServicesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dyy
 * @since 2025-05-27
 */
@RestController
@RequestMapping("/api/services")
public class ServicesController {

    @Autowired
    private IServicesService servicesService;

    // 添加服务项目
    @PostMapping
    public RestBean<Void> addService(@RequestBody Services service) {
        boolean save = servicesService.save(service);
        return this.messageHandle(save);
    }

    // 删除服务项目
    @DeleteMapping("/{id}")
    public RestBean<Void> deleteService(@PathVariable Integer id) {
        boolean save = servicesService.removeById(id);
        return this.messageHandle(save);
    }

    // 更新服务项目
    @PutMapping("/{id}")
    public RestBean<Void> updateService(@PathVariable Integer id, @RequestBody Services service) {
        service.setId(id);
        boolean save = servicesService.updateById(service);
        return messageHandle(save);
    }
    // 根据 ID 查询单个服务项目
    @GetMapping("/{id}")
    public RestBean<Services> getService(@PathVariable Integer id) {
        Services services = servicesService.getById(id);
        return RestBean.success(services);
    }
    // 分页查询服务项目
    @GetMapping("/page")
    public RestBean<Page<Services>> getServicesByPage(@RequestParam Integer current, @RequestParam Integer size) {
        Page<Services> page = new Page<>(current, size);
        return RestBean.success(servicesService.page(page));
    }
    // 分页查询服务项目
    @GetMapping("/page/condition")
    public RestBean<Page<Services>> getServicesByPage(
            @RequestParam Integer current,
            @RequestParam Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) BigDecimal price) {
        Page<Services> page = new Page<>(current, size);
        LambdaQueryWrapper<Services> queryWrapper = new LambdaQueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            queryWrapper.like(Services::getName, name);
        }
        if (price != null) {
            queryWrapper.eq(Services::getPrice, price);
        }
        return RestBean.success(servicesService.page(page, queryWrapper));
    }


    private RestBean<Void> messageHandle(boolean action){
        boolean message = action;
        return message==true?RestBean.success():RestBean.failure(400,"操作服务项目错误");
    }
}
